package com.pt25.base.dep.llm;


import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class LlmConfig {


    @Resource
    private LlmProperties llmProperties;

    @Bean
    Map<String, OpenAiChatModel> openAiChatModelHashMap() {
        Map<String, OpenAiChatModel> openAiChatModelHashMap = new HashMap<>();
        if (null != llmProperties && null != llmProperties.getConfigs()) {
            llmProperties.getConfigs().forEach(llmConfig -> {
                if (ModelType.CHAT.getModelType().equals(llmConfig.getModelType())) {
                    openAiChatModelHashMap.put(llmConfig.getModelName(), OpenAiChatModel.builder()
                            .baseUrl(llmConfig.getBaseUrl())
                            .apiKey(llmConfig.getApiKey())
                            .modelName(llmConfig.getModelName())
                            .timeout(Duration.ofSeconds(llmConfig.getTimeout()))  // ✅ 添加超时控制
                            .logRequests(llmConfig.getLogRequests())  // ✅ 开启日志便于调试
                            .logResponses(llmConfig.getLogResponses())
                            .build());
                }
            });
        }
        return openAiChatModelHashMap;
    }

    @Bean
    Map<String, OpenAiStreamingChatModel> openAiStreamingChatModelHashMap() {
        Map<String, OpenAiStreamingChatModel> openAiStreamingChatModelHashMap = new HashMap<>();
        if (null != llmProperties && null != llmProperties.getConfigs()) {
            llmProperties.getConfigs().forEach(llmConfig -> {
                if (ModelType.CHAT.getModelType().equals(llmConfig.getModelType())) {
                    openAiStreamingChatModelHashMap.put(llmConfig.getModelName(), OpenAiStreamingChatModel.builder()
                            .baseUrl(llmConfig.getBaseUrl())
                            .apiKey(llmConfig.getApiKey())
                            .modelName(llmConfig.getModelName())
                            .timeout(Duration.ofSeconds(llmConfig.getTimeout()))  // ✅ 添加超时控制
                            .logRequests(llmConfig.getLogRequests())  // ✅ 开启日志便于调试
                            .logResponses(llmConfig.getLogResponses())
                            .build());
                }
            });
        }
        return openAiStreamingChatModelHashMap;
    }


    @Getter
    @NoArgsConstructor
    @AllArgsConstructor
    enum ModelType {
        CHAT("chat"), STREAMING_CHAT("streaming-chat");
        private String modelType;
    }

}
